import React from 'react'
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button,Message,Radio,TreeSelect,DatePicker } from 'antd';
import moment from 'moment';
import AreaCascader from '../../Cascader/AreaCascader';
import SelectMarker from '../../AMap/SelectMarker';
import CommunityCascader from '../../Cascader/CommunityCascader';
import api from '../../../api/acoustic';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const dateFormat = 'YYYY/MM/DD hh:mm:ss';
const { MonthPicker, RangePicker } = DatePicker;

import './index.less'

class AcouticForm extends React.Component {
  state = {
    confirmDirty: false,
  };
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {   //提交后得到from表单中得值
      values.areaId=values.areaId[values.areaId.length-1]  //设置最后一个数
      if(values.id!=null){
        values.longitude=values.longitude_latitudeEdit[0]  //设置经度
        values.latitude=values.longitude_latitudeEdit[1]  //设置纬度
      }else{
        values.longitude=values.longitude_latitudeAdd[0]  //设置经度
        values.latitude=values.longitude_latitudeAdd[1]  //设置纬度
      }
      values.relateId=values.community[values.community.length-1] //设置级联relateId

      if (!err) {
        if(values.id){
            this.updateHard(values);
        }else{
             this.addHard(values);
        }
      }
    });
  }
  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }
  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('Two passwords that you enter is inconsistent!');
    } else {
      callback();
    }
  }
  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  addHard = (values) => {
    api.post('/addHard', values).then((data) => {
      const {addfinish} = this.props;
      const result=data.data;
      if(result.code==0){
         Message.success(result.message);
          addfinish();
      }else{
          Message.error(result.message);
      }
    });
  }
  updateHard = (values) => {
    api.put('/updateHard', values).then((data) => {
          const result=data.data;
          const {upfinish} = this.props;
           if(result.code==0){
             Message.success(result.message);
              upfinish();
           }else{
             Message.error(result.message);
           }
    });
  }


  validLoginNameRule = (rule, value, callback) => {
    const formData = this.props.form.getFieldsValue();
    const hardId=formData.hardequiid;
    const hardPwd=formData.hardpwd;
    api.get('/sysUser/getRegisterTargetCount', {"target":hardId,"devicePpassword":hardPwd}).then((data) => {
      const result= data.data;
      const areahardId = this.props.area;
      if(areahardId && areahardId.hardequiid == hardId){
        callback();
        return;
      }
     if(result.count == 0){
      callback('设备ID不正确，请检查!');
     }else if(result.count == 1){
      callback('该设备已添加!');
     }else if(result.count ==2){
      callback();
     }else if(result.count ==3){
      callback("有相同的设备，请输入密码匹配");
     }
    });
  }

  validLoginhardPwdRule = (rule, value, callback) => {
    const formData = this.props.form.getFieldsValue();
    const hardId=formData.hardequiid;
    const hardPwd=formData.hardpwd;
    api.get('/sysUser/getRegisterTargetCount', {"target":hardId,"devicePpassword":hardPwd}).then((data) => {
      const result= data.data;
      const areahardId = this.props.area;
      if(areahardId && areahardId.hardequiid == hardId){
        callback();
        return;
      }
      if(areahardId && areahardId.hardpwd == hardPwd){
        callback();
        return;
      }

      if(result.count == 0){
        callback('设备对应的密码不正确，请检查!');
       }else if(result.count == 1){
        callback('该设备已添加!');
       }else if(result.count ==2){
        callback();
       }
     if(result.count > 0){
      callback();
     }else{
     
     }
    });
  }



  //选择级联
  validLoginCommunityRule = (rule, value, callback) => {
    const formData = this.props.form.getFieldsValue();
     //处理连级
     if(formData.community.length<2){
        callback('至少选择两级!');
     }else{
        callback();
     }
  }

  render() {
    const { getFieldDecorator,resetFields } = this.props.form;
    const { close , callbackParent ,roles,offices,area,officesId} = this.props;
    const hardinfo = this.props.hardinfo;
    // 把重置表单的方法传给父亲
    callbackParent({
      resetFields:resetFields
    });

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem>
          {getFieldDecorator('id', {
              initialValue:hardinfo ? hardinfo.id : ''
          })(
            <Input type="hidden"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="设备名称"
          hasFeedback
        >
          {getFieldDecorator('name', {
            rules: [ {
              required: true, message: '设备名称', 
            }],
            initialValue:hardinfo ? hardinfo.name : ''
          })(
            <Input />
          )}
        </FormItem>
         <FormItem
          {...formItemLayout}
          label="设备序列号"
          hasFeedback
        >
          {getFieldDecorator('hardequiid', {
             rules: [{
              required: true, message: '设备序列号'},
           /*  { validator: this.validLoginNameRule} */],
            initialValue:hardinfo ? hardinfo.hardequiid : ''
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="设备密码"
          hasFeedback
        >
          {getFieldDecorator('hardpwd', {
            rules: [ {
              required: true, message: '设备密码', },
           /*  { validator: this.validLoginhardPwdRule} */],
              initialValue:hardinfo ? hardinfo.hardpwd : ''
          })(
            <Input type="password"/>
          )}
        </FormItem>
        <FormItem
        style={{ display: "none" }}
          {...formItemLayout}
          label="设备类型"
          hasFeedback
        >
          {getFieldDecorator('type', {
            rules: [{
              required: true, message: '设备类型',
            }],
            initialValue:hardinfo ? hardinfo.type : 10
          })(
            <Select
            showSearch
            style={{ width: 200 }}
            placeholder="Select a person"
            optionFilterProp="children"
            disabled={true}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
           
           <option value={10}>声波锁离线版</option>
             {/* <option value={5}>人脸门闸</option>
            <option value={12}>家庭锁</option>
            <option value={14}>广告屏</option>  */}
            
          </Select>
          )}
        </FormItem>
        <FormItem
            style={(hardinfo != undefined && hardinfo != undefined) ? {} : { display: "none" }}
            {...formItemLayout}
            label="设备地图位置"
            hasFeedback
          >
            {getFieldDecorator('longitude_latitudeEdit', {
              rules: [{ type: "array", required: true, message: '小区地图位置必须选择' }],
              initialValue: hardinfo!=undefined ? (hardinfo.longitude != undefined && hardinfo.latitude != undefined) ? [hardinfo.longitude, hardinfo.latitude] : [106.504962, 29.533155]: [106.504962, 29.533155]
            })(
              <SelectMarker />
              )}
          </FormItem>

          <FormItem
            style={(hardinfo != undefined && hardinfo != undefined) ? { display: "none" } : {}}
            {...formItemLayout}
            label="设备地图位置"
            hasFeedback
          >
            {getFieldDecorator('longitude_latitudeAdd', {
              rules: [{ type: "array", required: hardinfo==undefined , message: '小区地图位置必须选择' }],
            })(
              <SelectMarker />
              )}
          </FormItem>
          
        <FormItem
          {...formItemLayout}
          label="区域"
          hasFeedback
        >
            {getFieldDecorator('areaId', {
              rules: [{type:"array", required: true, message: '测试报错' }],
              initialValue: hardinfo ? hardinfo.areaId : ""
            })(
              <AreaCascader maxLevel={3}/>
              )}
           </FormItem>
           <FormItem
            {...formItemLayout}
            label="小区"
            hasFeedback
          >
            {getFieldDecorator('community', {
              rules: [
                { type: "array", required: true, message: '小区报错' },
                { validator: this.validLoginCommunityRule}],
              initialValue:  hardinfo ? hardinfo.cshStructureId : ""
            })(
              <CommunityCascader  onChange={(values) => { console.log(values); }} />
              )}
          </FormItem>
       <FormItem
       style={{ display: "none" }}
          {...formItemLayout}
          label="设备所属代理商"
          hasFeedback
        >
          {getFieldDecorator('officeId', {
            rules: [{
              required: true, message: '设备所属代理商!',
            }],
            initialValue:hardinfo ? hardinfo.officeId : officesId[0].id
          })(
            <TreeSelect
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={offices}
            placeholder="请选择一个设备所属代理商"
            treeDefaultExpandAll
            disabled={true}
          />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="安装地址"
          hasFeedback
        >
          {getFieldDecorator('address', {
            rules: [ {
              required: true, message: '安装地址', },
            ],
              initialValue:hardinfo ? hardinfo.address : ''
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="备注"
          hasFeedback
        >
          {getFieldDecorator('remarks', {
              initialValue:hardinfo ? hardinfo.remarks : ''
          })(
            <TextArea rows={4} />
          )}
        </FormItem>
        <FormItem {...tailFormItemLayout}>
          <div>
            <Button type="primary" htmlType="submit" style={{marginRight:'10px'}}>确定</Button>
            <Button onClick={close}>取消</Button>
          </div>
        </FormItem>
      </Form>
    );
  }
}

const WrappedAcouticForm = Form.create()(AcouticForm);
export default WrappedAcouticForm
